package com.example.myapplication;

import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class AddBookActivity extends AppCompatActivity {
    private ImageView img;
    private BookDatabaseHelper dbHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_add_books);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        dbHelper = new BookDatabaseHelper(this);
        img = findViewById(R.id.btn_back);
        img.setOnClickListener(v->{
            finish();
        });
        // 初始化视图
        EditText bookTitle = findViewById(R.id.book_title);
        EditText author = findViewById(R.id.author);
        EditText price = findViewById(R.id.price);
        EditText publisher = findViewById(R.id.publisher);
        EditText remarks = findViewById(R.id.remarks);
        Button addBookButton = findViewById(R.id.add_book_button);

        // 添加书籍按钮的点击事件
        addBookButton.setOnClickListener(v -> {
            String title = bookTitle.getText().toString();
            String authorName = author.getText().toString();
            String bookPrice = price.getText().toString();
            String publisherName = publisher.getText().toString();
            String remark = remarks.getText().toString();

            long result = dbHelper.addBook(title, authorName, bookPrice, publisherName, remark);

            if (result != -1) {
                Toast.makeText(this, "书籍信息已保存", Toast.LENGTH_SHORT).show();
                finish(); // 保存后返回
            } else {
                Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
}